package com.example.springbootdemo.config.mybaitsPlus;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.example.springbootdemo.utils.SequenceUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * 功能说明：
 * 开发人员:xuwangqi
 * 开发时间: 2020/10/17 <br>
 * 功能描述:  <br>
 */
@Configuration
@MapperScan({
        "com.example.springbootdemo.mall.mapper",
        "com.example.springbootdemo.scene.mapper"
})
public class MybatisPlusConfig {
  /**
   * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题
   */
  @Bean
  public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
    return interceptor;
  }

  /**
   *  注入自定义的自动填充 时间 策略
   * create: wuzhen  2020/11/16
   */
  @Bean
  public MetaObjectHandler myMetaObjectHandler(){
    return new MetaObjectHandler() {
      @Override
      public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("gmtCreate", LocalDateTime.now(),metaObject);
        this.setFieldValByName("gmtModified", LocalDateTime.now(),metaObject);
      }

      @Override
      public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("gmtModified", LocalDateTime.now(),metaObject);
      }
    };
  }

  /**
   *  mybatisPlus 自定义主键生成
   * create: wuzhen  2020/11/16
   *
   */
  @Bean
  public IdentifierGenerator myIdentifierGenerator(){
    return new IdentifierGenerator() {
      @Override
      public Number nextId(Object entity) {
        return SequenceUtils.nextId();
      }
    };
  }
}
